<template>
<div>
  <!--分类拖拽功能开关-->
  <el-switch
    v-model="draggable"
    active-text="开启拖拽"
    inactive-text="关闭拖拽">
  </el-switch>
  <el-button @click="batchSave" v-if="draggable" type="success" icon="el-icon-check" size="mini">保存</el-button>
  <el-button type="danger" icon="el-icon-delete" @click="batchDel" size="mini">批量删除</el-button>
  <!--tree导航树-->
  <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" :expand-on-click-node="false" show-checkbox node-key="catId" :draggable="draggable"
           :allow-drop="allowDrop"
           :allow-drag="allowDrag"
           @node-drop="handleDrop"
           ref="tree"
           :default-expanded-keys="expandedKey">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <span>{{ node.label }}</span>
        <span>
          <el-button type="text" v-if="node.level<=2" size="mini" @click="() => append(data)">Append</el-button>
          <el-button type="text"  v-if="node.childNodes.length==0" size="mini" @click="() => remove(node, data)">Delete</el-button>
          <el-button type="text"  size="mini" @click="edit(data)">Edit</el-button>
        </span>
      </span>
  </el-tree>
  <!--对话框，增加导航-->
  <el-dialog
    :title="dialogTitle"
    :visible.sync="dialogVisible"
    width="30%" :close-on-click-modal="false">
    <span>
      <el-form :model="category">
    <el-form-item label="分类名" >
      <el-input v-model="category.name" autocomplete="off"></el-input>
    </el-form-item>
    <el-form-item label="图标" >
      <el-input v-model="category.icon" autocomplete="off"></el-input>
    </el-form-item>
        <el-form-item label="计量单位" >
      <el-input v-model="category.productUnit" autocomplete="off"></el-input>
    </el-form-item>

  </el-form>
    </span>
    <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitData">确 定</el-button>
  </span>
  </el-dialog>
</div>
</template>

<script>
    import common from "../../../store/modules/common";

    export default {
        name: "category",
      data(){
          return{
            pCid:[],
            draggable:false,
            updataNodes:[],
            maxLevel:1,
            dialogTitle:"提示",
            dialogType:"",//edit,add
            category:{
              name:"",
              parentCid:0,
              catLevel:0,
              showStatus:1,
              sort:0,
              catId:null,
              icon:"",
              productUnit:"",
            },
            dialogVisible:false,
            expandedKey:[],
            data:null,
            defaultProps: {
              children: 'children',
              label: 'name'
            }
          }
      },
      methods:{
        //  批量删除按钮
        batchDel(){
          this.$confirm(`是否删除菜单?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$http({
              url: this.$http.adornUrl('/gulimallproduct/category/delete'),
              method: 'post',
              data:this.$http.adornData(this.$refs.tree.getCheckedKeys(),false)
            }).then(res=> {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
              //刷新出新的菜单
              this.getMenus();
            })
          }).catch(()=>{

          })

        },
        batchSave(){
          this.$http({
            url: this.$http.adornUrl('/gulimallproduct/category/update/sort'),
            method: 'post',
            data:this.$http.adornData(this.updataNodes,false)
          }).then(res=> {
            this.$message({
              message: '拖拽成功',
              type: 'success'
            });
            console.log(this.pCid)

            //刷新出新的菜单
            this.getMenus();
            //  设置默认需要展开的菜单
            this.expandedKey=this.pCid
            this.dialogVisible=false
          })



          this.updataNodes=[]
          this.maxLevel=0
          // this.pCid=0
        },
        //  拖拽事件成功后执行的方法
        handleDrop(draggingNode, dropNode, dropType, ev) {
        //  1、当前节点最新的父节点id
          let pCid=0
          let siblings=null;
          if (dropType=="before"||dropType=="after"){
            pCid=dropNode.parent.data.catId !=undefined? dropNode.parent.data.catId:0;
          } else{
            pCid=dropNode.data.catId;
          }
          this.pCid.push(pCid);
          console.log(this.pCid)

        //  2、当前脱宅节点的最新顺序
          if (dropType=="before"||dropType=="after"){
            siblings=dropNode.parent.childNodes;
          }else{
            siblings=dropNode.childNodes;
          }
          // console.log(siblings)
        //  3、当前拖拽节点的最新层级
          for (let i = 0; i <siblings.length ; i++) {
            if (siblings[i].data.catId==draggingNode.data.catId){
              let catLevel=draggingNode.data.level
              if (siblings[i].level!=draggingNode.level){
              //  当前节点的层级是否发生变化
                catLevel=siblings[i].level;
              //  修改子节点的层级
                this.updataChildNodeLevel(siblings[i]);
              }
              this.updataNodes.push({catId:siblings[i].data.catId,sort:i,parentCid:pCid,catLevel})
            } else {
              this.updataNodes.push({catId:siblings[i].data.catId,sort:i})
            }
          }
          console.log(this.updataNodes)

        },
        updataChildNodeLevel(node){
          if (node.childNodes.length>0){
            for (let i = 0; i < node.childNodes.length ; i++) {
              var cnode=node.childNodes[i].data;
              this.updataNodes.push({catId:cnode.catId,catLevel:node.childNodes[i].level});
              this.updataChildNodeLevel(node.childNodes[i])
            }
          }

        },
        allowDrop(draggingNode, dropNode, type){
       // 1、被拖动的当前节点以及所在父节点总层数不能大于3
       //    console.log("allowDrop",draggingNode,dropNode,type)
        //  1）、被拖动的当前节点总层数
          this.countNodeLevel(draggingNode)
          console.log("draggingNode",draggingNode)
          console.log("maxLevel",this.maxLevel)
        //  当前正在拖动的节点，加上父节点所在的深度不大于3即可
        //  Math.abs(),绝对值处理
          let deep=Math.abs(this.maxLevel-draggingNode.level)+1
          console.log("deep",deep)
          this.maxLevel=0;
          if (type == "inner"){
            console.log('inner',(deep+dropNode.level))
            return (deep+dropNode.level) <=3
          }else{
            console.log('after before',(dropNode.parent.level))
            return (deep+dropNode.parent.level) <=3
          }


        },
        countNodeLevel(node){
          //找到所有子节点，求到最大深度
          if (node.childNodes!=null&& node.childNodes.length>0){
            for (let i = 0; i < node.childNodes.length; i++) {
              if (node.childNodes[i].level >this.maxLevel) {
                this.maxLevel=node.childNodes[i].level
              }
              this.countNodeLevel(node.childNodes[i])
            }
          }else{
            if (node.level >this.maxLevel) {
              this.maxLevel=node.level
            }
          }
        },
        allowDrag(draggingNode) {
          return true;
        },
        //  tree修改按钮
        edit(data){
          this.dialogType="edit"
          this.dialogTitle="修改分类"
          console.log(data)
          this.dialogVisible=true
          //表单数据回显
          //发送请求获取当前节点最新的数据
          this.$http({
            url: this.$http.adornUrl(`/gulimallproduct/category/info/${data.catId}`),
            method: 'get'
          }).then(res=>{
            console.log("请求成功",res)
            // this.category.name=res.data.category.name
            // this.category.catId=dres.data.category.catId
            // this.category.icon=dres.data.category.icon
            // this.category.productUnit=dres.data.category.productUnit
            this.category=res.data.category
          })
        },
        submitData(data){
          if (this.dialogType=="add"){
            this.addCategory()
          }
          if (this.dialogType=="edit") {
            this.editCategory()
          }
        },
          //增加三级分类
        addCategory(){
         console.log(this.category)
          this.$http({
            url: this.$http.adornUrl('/gulimallproduct/category/save'),
            method: 'post',
            data:this.$http.adornData(this.category,false)
          }).then(res=> {
            this.$message({
              message: '新增成功',
              type: 'success'
            });
            //  设置默认需要展开的菜单
            this.expandedKey=[this.category.parentCid]
            //刷新出新的菜单
            this.getMenus();
            this.dialogVisible=false
          })
        },
        //修改三级分类
        editCategory(){
          this.$http({
            url: this.$http.adornUrl('/gulimallproduct/category/update'),
            method: 'post',
            data:this.$http.adornData(this.category,false)
          }).then(res=> {
            this.$message({
              message: '修改成功',
              type: 'success'
            });
            //  设置默认需要展开的菜单
            this.expandedKey=[this.category.parentCid]
            //刷新出新的菜单
            this.getMenus();
            this.dialogVisible=false
          })

        },
        //  打开增加菜单
        append(data) {
          this.dialogType="add";
          this.dialogTitle="新增分类"

          this.category.name=""
          this.category.parentCid=data.catId
          this.category.catLevel=data.catLevel*1+1
          this.category.catId=null
          this.category.showStatus=1
          this.category.sort=0
          this.category.icon=""
          this.category.productUnit=""

          this.dialogVisible = true
          this.category.parentCid=data.catId
          this.category.catLevel=data.catLevel*1+1

        },
        //删除菜单
        remove(node, data) {
          //弹窗提示
          this.$confirm(`是否删除【${data.name}】菜单?`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {

            const ids=[data.catId]
            this.$http({
              url: this.$http.adornUrl('/gulimallproduct/category/delete'),
              method: 'post',
              data:this.$http.adornData(ids,false)
            }).then(res=>{
              this.$message({
                message: '菜单删除成功',
                type: 'success'
              });
              //  设置默认需要展开的菜单
              this.expandedKey=[node.parent.data.catId]
              //刷新出新的菜单
              this.getMenus();

            })


          }).catch(()=>{});



        },
        handleNodeClick(){

        },
        getMenus(){
          this.$http({
            url: this.$http.adornUrl('/gulimallproduct/category/list/tree'),
            method: 'get'
          }).then(res=>{
            console.log("成功获取到数据",res)
            this.data=res.data.data
          })
        }

      },
      activated(){
         this.getMenus();
      }
    }
</script>

<style scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
</style>
